import exceptions.BussException;

import java.util.concurrent.*;

/**
 * Future的实现类为{@link FutureTask}, 直接看源码吧
 */
public class FutureCallTest {

    public static void main(String[] args) {
        boolean flag = false;
        System.out.println("start!!!");
        final ExecutorService exec = Executors.newFixedThreadPool(1);
        Callable<String> call = () -> {
            // 耗时操作
            if (flag) {
                throw new BussException("自定义异常");
            }
            Thread.sleep(2000);
            return "结果";
        };
        String ret = "init";
        Future<String> future = exec.submit(call);
        try {
            ret = future.get(5000, TimeUnit.MILLISECONDS); // 超时则直接抛TimeoutException
            System.out.println("任务成功返回:" + ret);
        } catch (TimeoutException e) {
            System.out.println("处理超时啦:" + ret);
        } catch (InterruptedException e) {
            System.out.println("中断异常:" + ret);
        } catch (ExecutionException e) {
            System.out.println("执行异常:" + ret);
        } catch (BussException e) {
            System.out.println("Bus bus!!!:" + ret);
        }
        exec.shutdown();
    }
}